﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Windows.Forms;
using static BW.Mes.WinForms.BasicData.MaterialForm;
using System.Collections.Generic;

namespace BW.Mes.WinForms.BasicData
{
    public partial class AddMaterialGroupForm : XtraForm
    {
        public AddMaterialGroupForm()
        {
            InitializeComponent();
            comboBoxEditType.Properties.Items.AddRange(new string[] { "原材料", "半成品", "成品", "其他" });
            this.Load += AddMaterialGroupForm_AutoGenMaterialCode;
        }

        private async void AddMaterialGroupForm_AutoGenMaterialCode(object sender, EventArgs e)
        {
            // 自动生成物料编号
            string today = DateTime.Now.ToString("yyyyMMdd");
            string prefix = $"WL{today}";
            int maxSerial = 0;
            try
            {
                var handler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (req, cert, chain, errors) => true
                };
                using (var client = new HttpClient(handler))
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                    var response = await client.GetAsync("T2/Material/GetMaterial");
                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();
                        var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(json);
                        var listToken = jsonObject["pageDatas"] ?? jsonObject["data"] ?? jsonObject["result"];
                        if (listToken != null)
                        {
                            var materials = JsonConvert.DeserializeObject<List<MaterialModel>>(listToken.ToString());
                            if (materials != null)
                            {
                                foreach (var item in materials)
                                {
                                    string code = item.MaterialCode;
                                    if (!string.IsNullOrEmpty(code) && code.StartsWith(prefix))
                                    {
                                        string serialStr = code.Substring(prefix.Length);
                                        if (int.TryParse(serialStr, out int serial))
                                        {
                                            if (serial > maxSerial) maxSerial = serial;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch { }
            string newCode = $"{prefix}{(maxSerial + 1).ToString("D3")}";
            textEditCode.Text = newCode;
            textEditCode.Properties.ReadOnly = true;
        }

        private async void btnOK_Click(object sender, EventArgs e)
        {
            var model = new
            {
                MaterialCode = textEditCode.Text,
                MaterialName = textEditName.Text,
                MaterialMsg = textEditMsg.Text,
                MaterialType = comboBoxEditType.Text,
                Routing = textEditProcessRoute.Text,
                CreatedBy = "wyj"
            };

            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (req, cert, chain, errors) => true
            };

            using (var client = new HttpClient(handler))
            {
                client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                var json = JsonConvert.SerializeObject(model);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await client.PostAsync("T2/Material/AddMaterial", content);

                if (response.IsSuccessStatusCode)
                {
                    XtraMessageBox.Show("添加成功！");
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    string errorContent = await response.Content.ReadAsStringAsync();
                    XtraMessageBox.Show($"添加失败：{response.ReasonPhrase} - {errorContent}");
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void AddMaterialGroupForm_Load(object sender, EventArgs e)
        {

        }
    }
}